package com.example.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求用户信息持有者
 * 用于在普通类和控制器中方便地获取当前登录用户信息
 */
public class RequestUserHolder {

    /**
     * 获取当前登录用户ID
     */
    public static Long getUserId() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        
        Object userId = request.getAttribute("userId");
        return userId != null ? (Long) userId : null;
    }

    /**
     * 获取当前登录用户名
     */
    public static String getUsername() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        
        Object username = request.getAttribute("username");
        return username != null ? (String) username : null;
    }

    /**
     * 获取请求中的属性值
     */
    public static Object getAttribute(String name) {
        HttpServletRequest request = getRequest();
        return request != null ? request.getAttribute(name) : null;
    }
    
    /**
     * 获取当前请求
     */
    private static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }
} 